package com.gotkicry.foodmenu;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InfoActivity extends AppCompatActivity {
    private static final String TAG = "InfoActivity";
    /**
     * 菜谱
     */
    private TextView mTextInclude;
    private ImageView mImgInfo;
    private TextView mTextJianjie;
    private TextView mTextMingxi;
    private MyListView mMylistview;
    private List<Map> list;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            MyAdapter adapter = new MyAdapter(list);
            mMylistview.setAdapter(adapter);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        initView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        String s = intent.getStringExtra("id");
        Log.d(TAG, "initData: " + s);
        String url = "http://apis.juhe.cn/cook/queryid?id=" + s + "&key=4c418590b697b3860fd06132a2cdfe2f";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                if (jsonObject.optString("reason").equals("Success")) {
                    try {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                        JSONArray jsonArray = jsonObject1.getJSONArray("data");
                        JSONObject jsb = jsonArray.getJSONObject(0);
                        mTextInclude.setText(jsb.getString("title"));
                        JSONArray jar = jsb.getJSONArray("albums");
                        mImgInfo.setTag(jar.getString(0));
                        String s = jar.getString(0);
                        showImageByAsynTask(mImgInfo, s);
                        mTextJianjie.setText(jsb.getString("imtro"));
                        mTextMingxi.setText(jsb.getString("burden"));
                        JSONArray jsonArray1 = jsb.getJSONArray("steps");
                        for(int i = 0 ; i < jsonArray1.length() ; i ++){
                            JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
                            Map<String,String> map = new HashMap<>();
                            map.put("imgUrl",jsonObject2.getString("img"));
                            map.put("info",jsonObject2.getString("step"));
                            list.add(map);
                        }
                        handler.sendEmptyMessage(0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });

        requestQueue.add(request);
    }

    private void initView() {
        list = new ArrayList<>();
        mTextInclude = (TextView) findViewById(R.id.text_include);
        mImgInfo = (ImageView) findViewById(R.id.img_info);
        mTextJianjie = (TextView) findViewById(R.id.text_jianjie);
        mTextMingxi = (TextView) findViewById(R.id.text_mingxi);
        mMylistview = (MyListView) findViewById(R.id.listview_my);
    }

    Bitmap BitmapByNetWork(String url) {
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL mUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
            is = new BufferedInputStream(connection.getInputStream());
            bitmap = BitmapFactory.decodeStream(is);
            connection.disconnect();
            return bitmap;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    void showImageByAsynTask(ImageView iv, String s) {
        new NewAsyncTask(iv, s).execute(s);
    }

    class NewAsyncTask extends AsyncTask<String, Void, Bitmap> {
        private ImageView imageView;
        private String mUrl;

        public NewAsyncTask(ImageView imageView, String mUrl) {
            this.imageView = imageView;
            this.mUrl = mUrl;
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            Log.d(TAG, "doInBackground: " + strings[0]);
            return BitmapByNetWork(strings[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (imageView.getTag().equals(mUrl)) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    class MyAdapter extends BaseAdapter {
        List<Map> list;

        public MyAdapter(List<Map> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;

            if(viewHolder == null){
                convertView = LayoutInflater.from(InfoActivity.this).inflate(R.layout.item_list_info, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            Map<String,String> map = list.get(position);
            String imgUrl = map.get("imgUrl");
            viewHolder.mImgItemInfo.setTag(imgUrl);
            showImageByAsynTask(viewHolder.mImgItemInfo,imgUrl);
            viewHolder.mTextItemInfo.setText(map.get("info"));
            return convertView;
        }

        class ViewHolder {
            View view;
            ImageView mImgItemInfo;
            TextView mTextItemInfo;

            ViewHolder(View view) {
                this.view = view;
                this.mImgItemInfo = (ImageView) view.findViewById(R.id.img_item_info);
                this.mTextItemInfo = (TextView) view.findViewById(R.id.text_item_info);
            }
        }
    }
}
